﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Security.Cryptography;
using System.Text;

namespace TinyPMS_Jerusalem.Models
{
    public class MySqlMembershipProvider: SqlMembershipProvider
    {
        public override bool ValidateUser(string username, string password)
        {
            DBModel.DBModelDataContext context = new DBModel.DBModelDataContext();
            var query = from g in context.aspnet_Users
                        where g.LoweredUserName == username.ToLower()
                        let userid = g.UserId
                        from c in context.aspnet_Membership
                        where c.UserId == userid
                        select c;
            if (query.Count() <= 0)
                return false;
            else
            {
                DBModel.aspnet_Membership memberShip = query.Single();
                string hashCode = EncodePassword(password, memberShip.PasswordFormat, memberShip.PasswordSalt);
                return hashCode == memberShip.Password;
            }
        }

        internal string GenerateSalt()
        {
            byte[] buffer = new byte[0x10];
            new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(buffer);
            return Convert.ToBase64String(buffer);
        }
        internal string EncodePassword(string pass, int passwordFormat, string salt)
        {
            if (passwordFormat == 0)
            {
                return pass;
            }
            // 将密码和salt值转换成字节形式并连接起来
            byte[] bytes = Encoding.Unicode.GetBytes(pass);
            byte[] src = Convert.FromBase64String(salt);
            byte[] dst = new byte[src.Length + bytes.Length];
            byte[] inArray = null;
            Buffer.BlockCopy(src, 0, dst, 0, src.Length);
            Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
            // 选择算法，对连接后的值进行散列
            if (passwordFormat == 1)
            {
                HashAlgorithm algorithm = HashAlgorithm.Create(Membership.HashAlgorithmType);
                inArray = algorithm.ComputeHash(dst);
            }
            else
            {
                inArray = this.EncryptPassword(dst);
            }
            // 以字符串形式返回散列值
            return Convert.ToBase64String(inArray);
        }
    }
}